<?php
/**
 * SDK 开发者接入的包
 *
 */
class SDK_Packages
{
    const _CONST_TB_DEFAULT_ = 'sdk_packages';
    protected static $_infos = array();
    protected static $_infos_dirty = TRUE;

    //
    // 返回开发者接入的包
    //
    // @param   string  status_key = <'invalid'|'valid'|'removed'>
    // @return  array()
    public static function lists ($status = NULL)
    {
        if ($status === NULL)
            $status = 'valid';

        $status = Kohana::config("SDK.package.status.$status");
        $query  = DB::select()
            ->from(self::_CONST_TB_DEFAULT_)
            ->where('status', '=', $status)
            ->order_by('ctime', 'DESC')
            ->execute();

        if ($query->valid())
            return $query->as_array();
        else
            return array();
    }

    public static function has_package ($pkgname)
    {
        self::load_all_infos ();
        foreach (self::$_infos as & $info)
        {
            if ($info['pkgname'] == $pkgname)
                return TRUE;
        }

        return FALSE;
    }

    public static function info ($package_id)
    {
        self::load_all_infos ();
        return Arr::get(self::$_infos, $package_id);
    }

    public static function package_id ($pkgname)
    {
        self::load_all_infos ();
        foreach (self::$_infos as & $info)
        {
            if ($info['pkgname'] == $pkgname)
                return $info['id'];
        }

        return 0;
    }

    protected static function load_all_infos ()
    {
        if (self::$_infos_dirty)
        {
            $query = DB::select()
                ->from(self::_CONST_TB_DEFAULT_)
                ->execute();

            $info = array();
            foreach ($query as $rs)
            {
                $id = $rs['id'];
                $info[$id] = $rs;
            }

            self::$_infos = $info;
            self::$_infos_dirty = FALSE;
        }
    }


    public function __construct ()
    {
        //
    }
}
